package cool.taomu.toolkit.service.kademlia.utils

import com.dampcake.bencode.Bencode
import com.dampcake.bencode.Type
import java.io.File
import java.io.FileInputStream
import java.util.HashMap
import java.util.Map
import org.apache.commons.io.FileUtils
import org.apache.commons.io.IOUtils
import java.util.ArrayList
import org.slf4j.LoggerFactory

class BEncodeUtils {

    val static LOG = LoggerFactory.getLogger(BEncodeUtils);

    def static synchronized write(Map<String, Object> dict, String filename) {
        write(dict, filename, false);
    }

    def static synchronized write(Map<String, Object> dict, String filename, boolean isUpdate) {
        var file = new File(filename);
        if (!file.exists || isUpdate) {
            var Bencode bencode = new Bencode();
            var byte[] encodedData = bencode.encode(dict);
            var str = new String(encodedData);
            FileUtils.write(file, str, "UTF-8")
        }
    }

    def static read(String fileanme) {
        LOG.info("开始解析 Bencode 格式文件:{}",fileanme)
        var Bencode bencode = new Bencode();
        try(var  fis = new FileInputStream(fileanme)) {
            var fisByte = IOUtils.toByteArray(fis)
            var Map<String, Object> decodedData = bencode.decode(fisByte, Type.DICTIONARY) as Map<String, Object>;
            return decodedData;
        } catch (Exception ex) {
            LOG.error(ex.message);
        }
    }

    def static getPieceHashes(byte[] pieces) {
        // 假设这是从 bencode 解析出的 pieces 字节数组
        var pieceHashes = new ArrayList<byte[]>();

        var int pieceLength = 20; // 每个 piece hash 是 20 字节的 SHA-1 值
        for (var int i = 0; i < pieces.length; i += pieceLength) {
            if (i + pieceLength > pieces.length) {
                throw new IllegalArgumentException("Invalid pieces data: length not multiple of 20");
            }

            var byte[] hash = newByteArrayOfSize(20)
            System.arraycopy(pieces, i, hash, 0, 20);
            pieceHashes.add(hash);
        }

        // 打印结果（调试用）
        LOG.debug("Number of piece hashes: " + pieceHashes.size());
        for (byte[] hash : pieceHashes) {
            LOG.debug(bytesToHex(hash));
        }
        return pieceHashes
    }

    // 辅助函数：将 byte[] 转换为十六进制字符串（便于查看）
    def static String bytesToHex(byte[] bytes) {
        var StringBuilder sb = new StringBuilder();
        for (byte b : bytes) {
            sb.append(String.format("%02x", b));
        }
        return sb.toString();
    }
}
